from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, HttpResponseForbidden
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response,redirect,render, get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.utils.encoding import smart_str
from django.contrib import auth, messages
from django.contrib.auth.models import User, Group
from django.contrib.auth.decorators import login_required
from account.models import *
from disn.utilities import *
from decimal import Decimal, getcontext
from django.contrib.auth.models import User, Group
from django.contrib import auth, messages
from django.contrib.auth.decorators import login_required
from disn.settings import WECHAT_ADMIN_USER_ID, BASE_DIR, DISN_HTTP_URL, APPID, DEBUG, TOKEN, ENCODING_AES_KEY, redis_instance, get_wechat_client
from taskqueue.tasks import send_user_consult_notification
from urllib.parse import unquote, quote
from wechatpy import parse_message
from wechatpy.utils import check_signature, ObjectDict
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.crypto import WeChatCrypto
from wechatpy.exceptions import InvalidSignatureException, InvalidAppIdException, WeChatClientException
from wechatpy.replies import TextReply, ImageReply, VoiceReply, ArticlesReply
from wechatpy.messages import *
from wechatpy.events   import *
import sys,hashlib,logging,uuid,json,os,traceback,time, random, string, requests
from disn.share_post import draw_user_post
from io import BytesIO

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

@csrf_exempt
def api(request):
    log.info('function api reload')
    wechat = get_wechat_client()
    echostr = request.GET.get('echostr', None)
    signature = request.GET.get('signature')
    msg_signature = request.GET.get('msg_signature')
    timestamp = request.GET.get('timestamp')
    nonce = request.GET.get('nonce')
    if request.method == 'GET' and echostr is not None and echostr != '':
        log.info('Starting check_signature ...')
        try:
            check_signature(TOKEN, signature, timestamp, nonce)
            return HttpResponse(echostr, content_type="text/plain")
        except InvalidSignatureException:
            return HttpResponseForbidden()
            # return HttpResponseBadRequest('Verify Failed')
    xml = request.body
    # log.info('xml=%s' %xml)
    crypto = WeChatCrypto(TOKEN, ENCODING_AES_KEY, APPID)
    try:
        decrypted_xml = crypto.decrypt_message(xml, msg_signature, timestamp, nonce)
    except (InvalidAppIdException, InvalidSignatureException):
        return HttpResponseForbidden()
    msg = parse_message(decrypted_xml)
    source = msg.source
    log.info('=' * 32 + 'New Message from [%s], msg.type:%s' %(source, msg.type) + '=' * 33)
    if isinstance(msg, TextMessage):
        log.info('Received type(%s) msg: %s' %(msg.type, msg.content))
    if isinstance(msg, BaseEvent):
        log.info('Received type(%s) msg: %s' %(msg.type, msg.event))
    # user_info_json = redis_instance.hget('subscribed_users', source)
    user_info_json = redis_instance.get(source)
    if not user_info_json:
        user_info_json = wechat.user.get(source)
        user_profile = UserProfile.get_create_or_update_user(user_info_json, msg, True)
        log.info('<<<fetch user_info_json from wechat server(call function get_user_info())>>>')
        if not isinstance(msg, UnsubscribeEvent):
            # redis_instance.hset('subscribed_users', source, user_info_json)
            redis_instance.set(source, user_info_json, ex=3600 * 48)
    else:
        user_info_json = user_info_json.decode()
        user_info_json=re.sub('\'','\"',user_info_json)
        user_info_json = json.loads(user_info_json)
        log.info('<<<fetch user_info_json from redis cache>>>')
        user_profile = UserProfile.get_create_or_update_user(user_info_json, msg, False)
    user = user_profile.user
    log.info(user_info_json)
    log.info('=' * 131)
    if isinstance(msg, UnsubscribeEvent):
        # redis_instance.hdel('subscribed_users', source)
        redis_instance.delete(source)
    response = None
    reply_msg = receive_msg = ''
    if user_profile is None:
        return HttpResponse('unsubscribe')
    save_path = './media/wechat/attachments/%s/' % user.id
    link_path = None
    file_name = sid()
    list_num_fmt = '(%d)%s'

    if isinstance(msg, ImageMessage) or isinstance(msg, VoiceMessage) or isinstance(msg, VideoMessage) or isinstance(msg, ShortVideoMessage):
        if not os.path.exists(save_path):
            os.makedirs(save_path)

    if isinstance(msg, TextMessage):
        receive_text = msg.content.strip()
        if user.is_active and user_profile.category == '0' and user.is_superuser:
            if receive_text == 'update_menu':
                try:
                    config = WxConfig.objects.get(status='1',category='4',key='menu')
                    wechat.menu.create(eval(config.value))
                    response = TextReply(content='微信菜单更新成功！', message=msg)
                except WxConfig.DoesNotExist:
                    response = TextReply(content='未找到微信菜单定义变量[menu]', message=msg)
            elif msg.content.lower() == 'not_subscribed':
                existed_openids = UserProfile.get_existed_wechat_openid()
                follower_json = wechat.user.get_followers()
                followers = follower_json['data']['openid']
                not_subscribed_list = []
                for _openid in existed_openids:
                    if not _openid in followers:
                        not_subscribed_customer = UserProfile.get_user_by_openid(_openid)
                        if not_subscribed_customer:
                            not_subscribed_list.append('%s:(%s)' %(not_subscribed_customer.nickname, _openid))
                        else:
                            not_subscribed_list.append('Unknow name:(%s)' %_openid)
                response = TextReply(content='\n'.join([list_num_fmt % (idx + 1, val) for idx, val in enumerate(not_subscribed_list)]), message=msg)

            elif msg.content.lower() == 'get_followers':
                existed_openids = UserProfile.get_existed_wechat_openid()
                follower_json = wechat.user.get_followers()
                followers = follower_json['data']['openid']
                subscribed_list = []
                for _openid in followers:
                    if not _openid in existed_openids and _openid != 'oFOmtwf_rCN4Riaku9zLDYLMA-tg':
                        new_user_info_json = wechat.user.get(_openid)
                        UserProfile.get_create_or_update_user(new_user_info_json, msg)
                followers_list_str = '\n'.join([list_num_fmt % (idx + 1, val) for idx, val in enumerate(followers)])
                response = TextReply(content=followers_list_str, message=msg)

            else:
                try:
                    config = WxConfig.objects.get(key='admin_%s' %receive_text,status='1',category='3')
                    if config.reply_type == 'text':
                        reply_msg = config.value
                        response = TextReply(content=reply_msg, message=msg)
                    elif config.reply_type == 'news':
                        response = ArticlesReply(message=msg, articles=eval(config.value))
                    else: # 默认发送文本
                        reply_msg = config.value
                        response = TextReply(content=reply_msg, message=msg)
                except WxConfig.DoesNotExist:
                    config = WxConfig()
                    config.key = 'admin_%s' %receive_text
                    config.value = 'admin_%s' %receive_text
                    config.status = '1'
                    config.category = '3'
                    config.save()
                    response = TextReply(content='新建微信自定义字符串[%s]' %config.key, message=msg)
        else:
            try:
                config = WxConfig.objects.get(key=receive_text,status='1',category='3')
            except WxConfig.DoesNotExist:
                items = Item.query_top_items_by(receive_text, 10)
                if items and len(items) > 0:
                    reply_msg = '为您查询到以下结果:\n'
                    for idx, val in enumerate(items):
                        reply_msg = '%s\n(%d)<a href="https://www.ztm.me/youhui/detail/%s/">[%s]%s|%s(%s)</a>\n' %(reply_msg, idx+1, val.id, val.article_mall, val.article_title, val.article_price, val.create_at)
                    ''' comment out for https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&announce_id=115383153198yAvN&version=&lang=zh_CN&token=
                    try:
                        banner_config = WxConfig.objects.get(key='SEARCH-BANNER', status='1', category='3')
                    except WxConfig.DoesNotExist:
                        banner_config = WxConfig()
                        banner_config.key = 'SEARCH-BANNER'
                        banner_config.status = '1'
                        banner_config.category = '3'
                        banner_config.value = 'https://img.ztm.me/2018/01/search.jpg'
                        banner_config.save()
                    response = ArticlesReply(message=msg)
                    response.add_article({
                        'title': '[%s]查询结果' % receive_text,
                        'image': banner_config.value,
                    })
                    for item in items:
                        response.add_article({
                            'title': item.article_title,
                            'image': 'https:%s' %item.qiniu_pic if item.qiniu_pic else '//img.ztm.me/img/noimg.png',
                            'url': 'https://www.ztm.me/youhui/detail/%s/' % item.pk
                        })
                    '''
                    response = TextReply(content=reply_msg, message=msg)
                    receive_msg = '用户查询%s(%s)' %(receive_text, msg.type)
                else:
                    try:
                        config = WxConfig.objects.get(key='auto_reply_text',status='1',category='3')
                    except WxConfig.DoesNotExist:
                        config = WxConfig()
                        config.key = 'auto_reply_text'
                        config.value = '我们已经收到您的留言。'
                        config.status = '1'
                        config.category = '3'
                        config.save()
                    else:
                        reply_msg = config.value
                        response = TextReply(content=reply_msg, message=msg)
                    receive_msg = '%s(%s)' %(receive_text, msg.type)
    elif isinstance(msg, VoiceMessage):
        receive_text = msg.recognition
        try:
            config = WxConfig.objects.get(key=receive_text, status='1', category='3')
        except WxConfig.DoesNotExist:
            try:
                config = WxConfig.objects.get(key='auto_reply_voice',status='1',category='3')
            except WxConfig.DoesNotExist:
                config = WxConfig()
                config.key = 'auto_reply_voice'
                config.value = '我们已经收到您的语音留言。'
                config.status = '1'
                config.category = '3'
                config.save()
        receive_msg = '%s(%s)' %(receive_text, msg.type)
        reply_msg = config.value
        response = TextReply(content=reply_msg, message=msg)
        resp = wechat.media.download(msg.media_id)
        save_path = '%s%s.%s' %(save_path, file_name, msg.format)
        link_path = './wechat/attachments/%s/' % user.id
        link_path = '%s%s.amr' %(link_path,file_name)
        log.info('save_path=%s' %save_path) # file_path=./wechat/attachments/jezhang/150611114353137791.jpg
        with open(save_path, 'wb') as fd:
            for chunk in resp.iter_content(1024):
                fd.write(chunk)
    elif isinstance(msg, ImageMessage):
        try:
            config = WxConfig.objects.get(key='auto_reply_image',status='1',category='3')
        except WxConfig.DoesNotExist:
            config = WxConfig()
            config.key = 'auto_reply_image'
            config.value = '我们已经收到您的图片。'
            config.status = '1'
            config.category = '3'
            config.save()
        reply_msg = config.value
        response = TextReply(content=reply_msg, message=msg)
        receive_msg = '收到图片(%s)' %msg.type
        resp = wechat.media.download(msg.media_id)
        save_path = '%s%s.jpg' %(save_path,file_name)
        link_path = './wechat/attachments/%s/' % user.id
        link_path = '%s%s.jpg' %(link_path,file_name)
        log.info('save_path=%s' %save_path)
        with open(save_path, 'wb') as fd:
            for chunk in resp.iter_content(1024):
                fd.write(chunk)
    elif isinstance(msg, VideoMessage):
        try:
            config = WxConfig.objects.get(key='auto_reply_video',status='1',category='3')
        except WxConfig.DoesNotExist:
            config = WxConfig()
            config.key = 'auto_reply_video'
            config.value = '我们已经收到您的视频。'
            config.status = '1'
            config.category = '3'
            config.save()
        reply_msg = config.value
        response = TextReply(content=reply_msg, message=msg)
        receive_msg = '收到视频(%s)' %msg.type
        resp = wechat.media.download(msg.media_id)
        save_path = '%s%s.mp4' %(save_path,file_name)
        link_path = './wechat/attachments/%s/' % user.id
        link_path = '%s%s.mp4' %(link_path,file_name)
        log.info('save_path=%s' %save_path)
        with open(save_path, 'wb') as fd:
            for chunk in resp.iter_content(1024):
                fd.write(chunk)
    elif isinstance(msg, ShortVideoMessage):
        try:
            config = WxConfig.objects.get(key='auto_reply_short_video',status='1',category='3')
        except WxConfig.DoesNotExist:
            config = WxConfig()
            config.key = 'auto_reply_short_video'
            config.value = '我们已经收到您的短视频。'
            config.status = '1'
            config.category = '3'
            config.save()
        reply_msg = config.value
        response = TextReply(content=reply_msg, message=msg)
        receive_msg = '收到短视频(%s)' %msg.type
        resp = wechat.media.download(msg.media_id)
        save_path = '%s%s.mp4' %(save_path,file_name)
        link_path = './wechat/attachments/%s/' % user.id
        link_path = '%s%s.mp4' %(link_path,file_name)
        log.info('save_path=%s' %save_path)
        with open(save_path, 'wb') as fd:
            for chunk in resp.iter_content(1024):
                fd.write(chunk)
    elif isinstance(msg, BaseEvent):  # 事件信息
        log.info('msg.event=%s' % msg.event)
        if msg.event == 'subscribe_scan' or msg.event == 'scan':
            scene_id = msg.scene_id
            receive_msg = None
            is_new_follower = False
            try:
                share = UserShare.objects.get(pk=scene_id, active=True)
                share_owner_profile = share.owner.profile
                notice_failure_msg = '发送消息给二维码主人[%s]失败！原因：超时或取消关注' %share_owner_profile.nickname
                if msg.event == 'subscribe_scan':
                    receive_msg = '未关注用户[%s]扫码(带参数)事件(%s),scene_id:%d' %(user_info_json.get('nickname',user_info_json.get('openid','')), msg.event, share.id)
                else:
                    receive_msg = '关注用户[%s]扫码(带参数)事件(%s),scene_id:%d' %(user_info_json.get('nickname',user_info_json.get('openid','')), msg.event, share.id)
                if share.owner == user:
                    response = TextReply(content='您扫了自己的二维码！😄', message=msg)
                    receive_msg = '%s\n%s' %(receive_msg, '用户扫了自己的二维码！')
                else:
                    user_share_follow, user_share_follow_created = UserShareFollow.objects.get_or_create(share=share, user=user)
                    if user_share_follow_created:
                        if msg.event == 'subscribe_scan':
                            if user_profile.subscribe_referrer: # 以前关注过
                                try:
                                    wechat.message.send_text(share_owner_profile.openid, '%s 已经是我们的老朋友啦！😄' %user_info_json['nickname'], account=None)
                                    receive_msg = '%s\n%s' %(receive_msg, '用户分享了二维码给以前关注过又取消关注的用户！')
                                except WeChatClientException:
                                    log.info('%s, response out of time limit or subscription is canceled' % share_owner_profile.openid)
                                    receive_msg = '%s\n%s' %(receive_msg, notice_failure_msg)
                            else:
                                user_profile.subscribe_referrer = share.owner
                                user_profile.save()
                                is_new_follower = True
                                share_owner_profile.point += 10
                                share_owner_profile.save()
                                try:
                                    wechat.message.send_text(share_owner_profile.openid, '%s 通过您的二维码成为我们的好朋友，您获得了10个积分，您的当前积分为：%d' % (user_info_json.get('nickname',''), share_owner_profile.point), account=None)
                                    receive_msg = '%s\n%s' %(receive_msg, '新用户[%s]通过[%s]的二维码关注我们，积分加10分' %(user_info_json['nickname'], share_owner_profile.nickname))
                                except WeChatClientException:
                                    log.info('%s, response out of time limit or subscription is canceled' % share_owner_profile.openid)
                                    receive_msg = '%s\n%s' %(receive_msg, notice_failure_msg)
                        else:
                            try:
                                wechat.message.send_text(share_owner_profile.openid, '%s 通过您的二维码查看了您推荐的内容' % user_info_json.get('nickname',''), account=None)
                                receive_msg = '%s\n%s' %(receive_msg, '[%s]扫了[%s]的二维码！' %(user_info_json.get('nickname','') , share_owner_profile.nickname))
                            except WeChatClientException:
                                log.info('%s, response out of time limit or subscription is canceled' % share_owner_profile.openid)
                                receive_msg = '%s\n%s' %(receive_msg, notice_failure_msg)
                    else:
                        try:
                            wechat.message.send_text(share_owner_profile.openid, '%s 通过您的二维码查看了您推荐的内容' % user_info_json.get('nickname',''), account=None)
                            receive_msg = '%s\n%s' %(receive_msg, '[%s]扫了[%s]的二维码' %(user_info_json.get('nickname','') , share_owner_profile.nickname))
                        except WeChatClientException:
                            log.info('%s, response out of time limit or subscription is canceled' % share_owner_profile.openid)
                            receive_msg = '%s\n%s' %(receive_msg, notice_failure_msg)
            except UserShare.DoesNotExist:
                if msg.event == 'subscribe_scan':
                    receive_msg = '未关注用户[%s]扫码(带参数)事件(%s),scene_id:%d不存在数据库中或到期' %(user_info_json.get('nickname',user_info_json.get('openid','')), msg.event, scene_id)
                else:
                    receive_msg = '关注用户[%s]扫码(带参数)事件(%s),scene_id:%d不存在数据库中或到期' %(user_info_json.get('nickname',user_info_json.get('openid','')), msg.event, scene_id)
            # reply user
            item = share.goods_item
            if item:
                if share.is_redirect:
                    url = 'http://www.ztm.me/youhui/detail/%d/?redirect=true' %item.id
                else:
                    url = 'http://www.ztm.me/youhui/detail/%d/' %item.id
                print('url=%s' %url)
                response = ArticlesReply(message=msg)
                response.add_article({
                    'title': item.article_title,
                    'description': item.article_summary,
                    'image': 'https:%s' % item.qiniu_pic if item.qiniu_pic else '//img.ztm.me/img/noimg.png' ,
                    'url': url
                })
                if is_new_follower:
                    response = TextReply(content='您通过 %s 的二维码成为我们的好朋友' % user_profile.subscribe_referrer.profile.nickname, message=msg)
                receive_msg = '%s\n%s' %(receive_msg, item.article_title)
            else:
                if is_new_follower:
                    response = TextReply(content='您通过 %s 的二维码成为我们的好朋友' % user_profile.subscribe_referrer.profile.nickname, message=msg)
                else:
                    response = TextReply(content='您已经是我们的老朋友啦！😄', message=msg)
        elif msg.event == 'subscribe':
            try:
                admin_user = User.objects.get(username='admin')
            except User.DoesNotExist:
                admin_user = User.objects.create_superuser('admin', 'jean.zhang@outlook.com', 'pass')
            try:
                config = WxConfig.objects.get(key='auto_reply_subscribe', category='3', reply_type='text', status = '1')
            except WxConfig.DoesNotExist:
                config = WxConfig()
                config.key = 'auto_reply_subscribe'
                config.value = '尊敬的%s，感谢关注我们！'
                config.status = '1'
                config.category = '3'
                config.reply_type = 'text'
                config.save()
            reply_msg = config.value % user_profile.nickname
            if config.status == '1':
                try:
                    wechat.message.send_text(user_profile.openid, reply_msg, account=None)
                except WeChatClientException:
                    log.info('%s, response out of time limit or subscription is canceled' % share_owner_profile.openid)
                # response = TextReply(content=reply_msg, message=msg)
            if user_profile.subscribe_referrer is None:
                user_profile.point += 10
                user_profile.subscribe_referrer = admin_user
                user_profile.save()
                try:
                    config = WxConfig.objects.get(key='auto_reply_first_subscribe', category='3', reply_type='text', status = '1')
                except WxConfig.DoesNotExist:
                    config = WxConfig()
                    config.key = 'auto_reply_first_subscribe'
                    config.value = '新用户免费获得10个积分，点击菜单“个人中心|我的专属海报”生成您的专属海报，分享海报给好友获得更多积分。'
                    config.status = '1'
                    config.category = '3'
                    config.reply_type = 'text'
                    config.save()
                try:
                    wechat.message.send_text(user_profile.openid, config.value, account=None)
                except WeChatClientException:
                    log.info('%s, response out of time limit or subscription is canceled' % share_owner_profile.openid)
            else:
                try:
                    config = WxConfig.objects.get(key='auto_reply_second_subscribe', category='3', reply_type='text', status = '1')
                except WxConfig.DoesNotExist:
                    config = WxConfig()
                    config.key = 'auto_reply_second_subscribe'
                    config.value = '谢谢您再次关注！🙏🙏🙏'
                    config.status = '1'
                    config.category = '3'
                    config.reply_type = 'text'
                    config.save()
                try:
                    wechat.message.send_text(user_profile.openid, config.value, account=None)
                except WeChatClientException:
                    log.info('%s, response out of time limit or subscription is canceled' % share_owner_profile.openid)
            try:
                config = WxConfig.objects.get(key='auto_reply_subscribe_card', category='3', reply_type='news')
            except WxConfig.DoesNotExist:
                config = WxConfig()
                config.key = 'auto_reply_subscribe_card'
                config.value = None
                config.status = '0'
                config.category = '3'
                config.reply_type = 'news'
                config.save()
            if config.status == '1':
                response = ArticlesReply(message=msg, articles=eval(config.value))

            receive_msg = '新用户关注事件(%s)' %msg.event
        elif msg.event == 'unsubscribe':
            receive_msg = '用户取消关注事件(%s)' %msg.event
        elif msg.event == 'click':
            if msg.key == "KEFUONLINE":
                hour = datetime.datetime.now().hour
                receive_msg = '用户请求人工客服(%s|%s)' %(msg.event,msg.key)
                if hour >= 9 and hour <= 18:
                    response = TransferCustomerServiceReply() # 会话转给客服
                else:
                    try:
                        config = WxConfig.objects.get(key='auto_kefu_offline',status='1',category='3')
                    except WxConfig.DoesNotExist:
                        config = WxConfig()
                        config.key = 'auto_kefu_offline'
                        config.value = '在线客服上班时间为早上9点到下午17点'
                        config.status = '1'
                        config.category = '3'
                        config.save()
                    reply_msg = config.value
                    response = TextReply(content=reply_msg, message=msg)
            elif msg.key == 'LATEST_NEWS':
                pass
            elif msg.key == 'MY_POSTER':
                qrcode_type = '0'
                # if user.is_staff and user.is_superuser:
                #     qrcode_type = '1'
                post_image = draw_user_post(user_profile=user_profile, qrcode_type=qrcode_type) # temporary=0 , permanent=1
                qrcode_path = '/tmp/%s.png' % source
                post_image.save(qrcode_path, 'PNG')
                upload_file = open(qrcode_path, 'rb')
                res = wechat.media.upload(media_type='image', media_file=upload_file)
                if 'media_id' in res:
                    media_id = res['media_id']
                    receive_msg = '用户[%s]请求制作海报(%s|%s)' %(user_info_json.get('nickname',user_info_json.get('openid','')), msg.event, msg.key)
                    response = ImageReply(media_id=media_id, message=msg)
                    try:
                        os.remove(qrcode_path)
                    except OSError:
                        pass
            else:
                try:
                    config = WxConfig.objects.get(key=msg.key,status='1',category='3')
                except WxConfig.DoesNotExist:
                    try:
                        config = WxConfig.objects.get(key=msg.key,status='1',category='3')
                    except WxConfig.DoesNotExist:
                        config = WxConfig()
                        config.key = msg.key
                        config.value = '请设置响应内容'
                        config.status = '1'
                        config.category = '3'
                        config.save()
                receive_msg = '%s(%s)' %(msg.key,msg.event)
                if config.reply_type == 'text':
                    reply_msg = config.value
                    response = TextReply(content=reply_msg, message=msg)
                elif config.reply_type == 'news':
                    response = ArticlesReply(message=msg, articles=eval(config.value))
                else: # 默认发送文本
                    reply_msg = config.value
                    response = TextReply(content=reply_msg, message=msg)
        elif msg.event == 'view':
            receive_msg = '用户请求页面事件(%s|%s)' %(msg.event,msg.url)
        elif msg.event == 'templatesendjobfinish':
            receive_msg = None
        elif msg.event == 'kf_create_session':
            receive_msg = '进入客服会话模式(%s)' %msg.event
        elif msg.event == 'kf_close_session':
            receive_msg = '退出客服会话模式(%s)' %msg.event
        else:
            receive_msg = '用户触发未知类型事件(%s)' %msg.event
    else:
        try:
            config = WxConfig.objects.get(key='auto_kefu_offline',status='1',category='3')
        except WxConfig.DoesNotExist:
            config = WxConfig()
            config.key = 'auto_kefu_offline'
            config.value = '我们已经收到您的未知类型文件。\n谢谢，祝您生活愉快!'
            config.status = '1'
            config.category = '3'
            config.save()
        reply_msg = config.value
        response = TextReply(content=reply_msg, message=msg)
        try:
            receive_msg = '未知类型(%s)' %msg.event
        except:
            receive_msg = '未知类型事件'
    if receive_msg:
        # notify admin
        if user.is_active and not user.is_staff:
            send_user_consult_notification.delay(first='微信用户操作提醒', username=user_info_json.get('nickname',source), content=receive_msg, remark=None, url=None)
        receive_log = WechatLog()
        receive_log.content = receive_msg
        receive_log.user = user_profile
        receive_log.msg_type = '1'
        if link_path:
            receive_log.attachment = link_path
        receive_log.save()
        # xml = response.render()
        # print(xml)
        # notify_rm(user=user, body='您有客户留言，请尽快回复!', leave_msg=receive_msg, remark='点击这里立即回复客户')
    return HttpResponse(response)


def get_jssdk_signature(request):
    if DEBUG:
        return None
    wechat = get_wechat_client()
    jsapi_ticket = wechat.jsapi.get_jsapi_ticket()
    # print('jsapi_ticket=%s' %jsapi_ticket)
    nonce_str= ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15))
    # print('noncestr=%s' %nonce_str)
    timestamp_int = int(time.time())
    # print('timestamp=%d' %timestamp_int)
    # url = 'http://' + request.META.get('HTTP_HOST')+request.META.get('PATH_INFO')+request.META.get('QUERY_STRING','')
    # url = 'https://' + request.META.get('HTTP_HOST')+request.META.get('PATH_INFO')
    # referrer = request.GET.get('referrer', None)
    # if referrer:
    #     if url.find('?') > 0:
    #         url = '%s&referrer=%s' %(url, referrer)
    #     else:
    #         url = '%s?referrer=%s' %(url, referrer)
    url = request.build_absolute_uri()
    print('get_jssdk_signature for url=%s' %url)
    tmpstr = 'jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s' %(jsapi_ticket,nonce_str,timestamp_int,url)
    tmpstr = tmpstr.encode('utf-8') # python3 need this line
    tmpstr = hashlib.sha1(tmpstr).hexdigest() # verify at http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
    # print('signature=%s' %tmpstr)
    jssdk_signature = {}
    jssdk_signature['timestamp']  = timestamp_int
    jssdk_signature['nonce'] = nonce_str
    jssdk_signature['signature'] = tmpstr
    jssdk_signature['appid'] = APPID
    return jssdk_signature

def jssdk_demo(request):
    return render(request, 'weui/weixin-jssdk.html', {'jssdk_signature':get_jssdk_signature(request)})

@csrf_exempt
def get_signature(request):
    url = request.POST.get('url')
    print ('%s():%s' %(request.method, url))
    return HttpResponse(json.dumps(get_jssdk_signature(request)), content_type="application/json")

@csrf_exempt
def save_followers(request):
    wechat = get_wechat_client()
    existed_openids = UserProfile.get_existed_wechat_openid()
    follower_json = wechat.get_followers()
    followers = follower_json['data']['openid']
    cnt = 0
    for _openid in followers:
        if not _openid in existed_openids and _openid != 'oFOmtwf_rCN4Riaku9zLDYLMA-tg':
            print ('[%s] not existed.' % _openid)
            new_user_info_json = wechat.get_user_info(_openid)
            UserProfile.get_create_or_update_user(new_user_info_json, 'subscribe')
            cnt += 1
    followers_list_str = '\n'.join(followers)
    return HttpResponse('Successfully saved [%d] followers!' %cnt)